<?php

namespace App\Admin\Extensions;

use Encore\Admin\Grid;
use Encore\Admin\Grid\Exporters\AbstractExporter;
use Maatwebsite\Excel\Facades\Excel;
use Encore\Admin\Grid\Column;

class ExcelExpoter extends AbstractExporter
{
    public $tablename = '';
    public $titles = [];

    public function __construct(Grid $grid = null, $name)
    {
        parent::__construct($grid);
        $this->tablename = $name;
    }

    public function export()
    {
        Excel::create($this->tablename . date('Y-m-d'), function ($excel) {

            /*$excel->setTitle('这是啥');
            $excel->setCreator('Creator这又是啥')->setCompany('Maatwebsite又是什么鬼');
            $excel->setDescription('Description这个好像挺长，写点啥呢');*/
            /*$columns = $this->grid->columns();
            if (!empty($columns)) {
                foreach ($columns as $c) {
                    array_push($this->titles, $c->getLabel());
                }
            }*/
            $excel->sheet($this->tablename, function ($sheet) {
                $this->grid->build();
                // 这段逻辑是从表格数据中取出需要导出的字段
                $modelColumnNames = [];
                $titleNames = [];
                $this->grid->columns()->map(function (Column $column) use (&$modelColumnNames, &$titleNames) {
                    if ($column->getName() != '__row_selector__' && $column->getName() != '__actions__') {
                        array_push($modelColumnNames, $column->getName());
                        array_push($titleNames, $column->getLabel());
                    }
                });
                $modelColumnNames = array_unique($modelColumnNames);
                $titleNames = array_unique($titleNames);
                $sheet->rows([$titleNames]);

                $rows = $this->grid->rows();
                $datas = $rows->map(function ($item) use ($modelColumnNames) {
                    $row = array();
                    $model = $item->model();
                    foreach ($modelColumnNames as $key) {
                        $row[$key] = strip_tags($model[$key]);
                    }
                    return $row;
                });
                $sheet->rows($datas);
            });

        })->export('xls');
    }
}